import { IncomingMessage, ServerResponse } from "http";

const getRouter = require('router');
const router = getRouter();
const animal = require('../model/animal');
const queryString = require('querystring');
const template = require('art-template');

router.get('/list', (req: IncomingMessage, res: ServerResponse) => {
  animal.find({})
    .then((result: any) => {
      res.writeHead(200, {
        'content-type': 'application/json;charset-utf9'
      })
      res.end(JSON.stringify(result));
    })
    .catch((err: any) => {
      // res.statusCode = 5001;
      res.end('宠物数据获取失败'+err);
  })
});

router.get('/listTpl', async (req: IncomingMessage, res: ServerResponse) => {
  let lists = await animal.find({});
  let html = template('list', { lists });
  res.end(html);
});

router.post('/add', (req: IncomingMessage, res: ServerResponse) => {
  let postParams: any = '';
  req.on('data', (chunk) => {
    postParams += chunk;
  });
  req.on('end', async() => {
    let postParamsObj = queryString.parse(postParams);
    console.log('add的数据是：', postParamsObj, postParams);
    try {
      let addItem = await animal.create(postParamsObj);
      // res.writeHead(301, {
      //   location: '/listTpl'
      // });
      // res.end();
      res.end(`${addItem.owner}恭喜您!宠物${addItem.name}(手机号${addItem.phone})注册成功！`)
    } catch (error) {
      res.end('很遗憾注册失败！');
      console.log('err=>', error);
    }
  });
});

module.exports = router;